package com.kylin.domain.oauth2.social;

import com.kylin.domain.oauth2.social.wechat.WechatSession;
import com.kylin.domain.user.vo.WechatUserInfoVO;
import com.kylin.shared.common.consts.Constants;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 微信缓存管理
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年11月30日 21:54
 */
@Component
@RequiredArgsConstructor
public class WechatCacheManager {

    private final StringRedisTemplate stringRedisTemplate;


    public void cache(String key, String value, long expiresIn) {
        this.stringRedisTemplate.opsForValue().set(key, value, expiresIn, TimeUnit.MILLISECONDS);
    }

    public String get(String key) {
        return this.stringRedisTemplate.opsForValue().get(key);
    }

    public void cacheLoginInfo(WechatUserInfoVO userInfo, WechatSession session) {
        // 缓存 sessionKey 与 userId 的对应关系
        this.cache(
                Constants.KEY_USERID_SESSION_KEY + userInfo.getUserId(),
                session.getSessionKey(),
                Constants.MILLI_2_HOURS
        );
        // 缓存 openId 与 userInfo 的对应关系
        this.cache(
                Constants.KEY_OPENID_USERINFO + session.getOpenId(),
                userInfo.toString(),
                Constants.MILLI_2_HOURS
        );
    }
}
